<template>
  <el-form :model="form"
           ref="form"
           class="add-bot-form"
           :rules="rules"
           @submit.native.prevent
           @keyup.enter.native="onSave"
           v-loading="loading">

    <el-form-item prop="name"
                  :label="$t('custom.botStore.name')">
      <el-input v-model="form.name"
                :maxlength="70"
                show-word-limit
                :placeholder="$t('custom.botStore.enterName')"></el-input>
    </el-form-item>
    <el-form-item prop="roleIdList"
                  :label="$t('custom.reports.role')">
      <el-select v-model="form.roleIdList"
                 filterable
                 clearable
                 multiple
                 collapse-tags
                 default-first-option
                 style="width:100%"
                 :placeholder="$t('custom.reports.role')">
        <el-option v-for="(item,index) in roleOptions"
                   :key="index"
                   :value="item.roleId"
                   :label="item.name"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="tagList"
                  :label="$t('custom.reports.tag')">
      <el-select v-model="form.tagList"
                 filterable
                 clearable
                 multiple
                 allow-create
                 collapse-tags
                 default-first-option
                 :placeholder="$t('custom.reports.tag')"
                 style="width: 100%;">
        <el-option v-for="(item,index) in tags"
                   :key="index"
                   :label="item.name"
                   :value="item.name"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item prop="description"
                  :label="$t('custom.botStore.description')">
      <el-input v-model="form.description"
                type="textarea"
                :maxlength="500"
                :rows="3"
                show-word-limit
                @keyup.enter.native.stop
                :placeholder="$t('custom.botStore.description')"></el-input>
    </el-form-item>

    <el-form-item class="text-right">
      <el-button type="text"
                 @click="moreEditVisible = true"
                 v-if="$hasPermission('sys:bots:moreedit')"
                 size="small">{{ $t('custom.reports.moreedit') }}</el-button>
      <el-button size="small"
                 @click="onReselect">Reselect</el-button>
      <el-button size="small"
                 type="primary"
                 @click="onSave">{{ $t('custom.reports.continue') }}</el-button>
    </el-form-item>

    <el-dialog width="470px"
               :title="$t('custom.reports.moreedit')"
               :visible.sync="moreEditVisible"
               append-to-body
               custom-class="more-dialog"
               destroy-on-close>
      <el-form :model="form"
               v-loading="moreLoading"
               ref="moreForm"
               class="more-edit-dialog-form "
               :rules="rules"
               @submit.native.prevent
               @keyup.enter.native="onSave"
               label-position="top">
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item prop="classification"
                          label="Template Type">
              <el-select v-model="form.classification"
                         :placeholder="$t('custom.bots.edit.classification')"
                         style="width: 100%;">
                <el-option v-for="item in classOptions"
                           :key="item.dictValue"
                           :label="item.dictLabel"
                           :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="businessType"
                          :label="$t('custom.dataset.businessType')">
              <el-select v-model="form.businessType"
                         :placeholder="$t('custom.dataset.businessType')"
                         style="width: 100%;"
                         :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                <el-option v-for="item in businessTypes"
                           :key="item.dictValue"
                           :label="item.dictLabel"
                           :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="status"
                          :label="$t('custom.dataset.status')">
              <el-select v-model="form.status"
                         :placeholder="$t('custom.dataset.status')"
                         style="width: 100%;"
                         :disabled="!$hasPermission('sys:tenant:model:allowtomanagesystemmodel')">
                <el-option v-for="item in statusList"
                           :key="item.dictValue"
                           :label="item.dictLabel"
                           :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="tenantCode"
                          :label="$t('custom.dataset.tenantCode')">
              <SelectClientId v-model="form.tenantCode"
                              :disabled="form.businessType==='Template' || form.businessType==='MSPbots Internal'"
                              :width="100" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="da"
                          :label="$t('custom.report.da')">
              <el-select v-model="form.da"
                         clearable
                         filterable
                         :placeholder="$t('custom.report.da')"
                         style="width: 100%;">
                <el-option v-for="items in users"
                           :key="items.id"
                           :label="items.realname"
                           :value="items.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="po"
                          :label="$t('custom.report.po')">
              <el-select v-model="form.po"
                         clearable
                         filterable
                         :placeholder="$t('custom.report.po')"
                         style="width: 100%;">
                <el-option v-for="items in users"
                           :key="items.id"
                           :label="items.realname"
                           :value="items.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="jiraNumber"
                          :label="$t('custom.reports.jiraNumber')">
              <el-input v-model="form.jiraNumber"
                        type="text"
                        style="width: 100%"
                        rows="3"
                        :placeholder="$t('custom.reports.jiraNumber')">
                <JiraNumberLink slot="suffix"
                                :jiraNumber="form.jiraNumber" />
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item prop="shared"
                          :label="$t('custom.dataset.shared')">
              <el-switch v-model="form.shared"
                         active-color="#007bff"
                         inactive-color="#dcdfe6">
              </el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="applyTenant"
                          v-if="$hasPermission('sys:bot:defaultinstall')"
                          :label="$t('custom.dataset.defaultInstall')">
              <el-switch v-model="form.applyTenant"
                         active-color="#007bff"
                         inactive-color="#dcdfe6">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template slot="footer">
        <el-button @click="moreEditVisible = false"
                   :loading="moreLoading"
                   size="small">{{ $t('Cancel') }}</el-button>
        <el-button type="primary"
                   @click="onSave"
                   :loading="moreLoading"
                   size="small">{{ $t('Save') }}</el-button>
      </template>
    </el-dialog>
  </el-form>
</template>

<script>
import useErrorMessage from '@/components/storybook/hooks/useErrorMessage'
import { intersectionBy, set, cloneDeep, get } from 'lodash'
import { optionList, uatList } from '../index.schema'
import JiraNumberLink, { JiraNumberMixin } from '@/components/jira-number-link'
import { useDicts, } from '@/components/storybook/hooks/useDict'
import getFlowSetting from '@/views/modules/mspbots/bots-bak/my-bots/TruggerTemplate'
import {
  fetchTag,
  fetchRole,
  fetchQuery,
  fetchAssignRole,
  createBot,
  matchJira,
  fetchBotTemplates,
  checkBotName
} from '@/api/new'
import { symbolReg } from '@/components/storybook/utilties/reg'

export default {
  name: 'AddBotForm',
  components: {
    JiraNumberLink

  },
  mixins: [JiraNumberMixin],
  props: {
    resourceType: [String, Number],
    row: {
      type: Object,
      required: true
    }
  },
  data () {

    return {
      form: {
        status: !this.$hasPermission('sys:bots:moreedit') ? 'Published' : 'Requested',
        businessType: this.$route.path.includes('CrossTenant') ? 'MSPbots Internal' : 'Custom',
        name: null,
        roleIdList: this.$store.state.defaultRoleList,
        description: null,
        newType: 0,
        tenantCode: this.$store.state.user.tenantCode,
        shared: false,
        applyTenant: false,
        teamId: '',
        classification: '',
        da: this.$store.state.user.id,
        po: '',
        jiraNumber: '',
        tagList: []
      },
      rules: {
        name: [
          { required: true, validator: this.validateName, trigger: 'blur' }
        ],
        roleIdList: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        // description: [
        //   { required: true, message: this.$t('validate.required'), trigger: 'blur' },
        // ],
        po: [
        //  { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        da: [
          { required: true, message: this.$t('validate.required'), trigger: 'change' }
        ],
        jiraNumber: [
        // { required: true, validator: this.validateJira, trigger: 'blur' }

        ],
        businessType: [
          { required: false, message: this.$t('custom.tips.required', { fields: 'Type' }), trigger: 'change' }
        ],
        tenantCode: [
          { required: false, message: this.$t('custom.tips.required', { fields: 'Client' }), trigger: 'change' }
        ],
        status: [
          { required: true, message: this.$t('custom.tips.required', { fields: 'Status' }), trigger: 'change' }
        ]
      },

      loading: false,
      moreLoading: false,
      moreEditVisible: false,

      optionList,
      uatList,
      roles: [],
      tags: [],
      users: [],
      roleOptions: [],
      assignRoles: [],
      businessTypes: [],
      statusList: [],
      templates: []
    }
  },
  computed: {

    classOptions () {
      return useDicts('bots_classification_list')
    }
  },
  created () {
    this.init()
  },
  methods: {
    async init () {
      try {
        this.loading = true
        const [roles, tags, assignRoles, users, businessTypes, statusList, templates] = await Promise.all([
          this.getRoles(),
          this.getTags(),
          this.getAssingRoles(),
          this.getUsers(),
          this.getBusinessTypes(),
          this.getStatusList(),
          this.getBotTemplates()
        ])
        this.roles = roles
        this.tags = tags
        this.users = users
        this.assignRoles = assignRoles
        this.templates = templates
        this.statusList = statusList
        this.businessTypes = businessTypes
        const assigns = this.assignRoles.map(item => ({
          ...item,
          roleId: item.assignId
        }))
        this.roleOptions = intersectionBy(this.roles, assigns, 'roleId')
        this.form.classification = get(this.row, '_classification', this.classOptions[0].dictValue)
      } catch (error) {
      } finally {
        this.loading = false
      }
    },

    async validateName (rule, value, callback) {
      if (!value) {
        throw new Error(this.$t('validate.required'))
      }
      try {
        const { name, id, businessType } = this.form
        let params = {
          name,
          id,
          businessType
        }
        if (!symbolReg.test(value)) {
          throw new Error(this.$t('validate.isIncludeSymbol'))
        }

        const { data: response } = await checkBotName(params)
        if (response.code !== 0) {
          throw new Error('The name is already exists')
        }
        callback()
      } catch (error) {
        callback(error)
      }
    },
    async validateJira (rule, value, callback) {

      try {
        if (!value) {
          throw new Error(this.$t('validate.required'))
        }

        let params = {
          issueIdOrKey: value
        }

        const isMatchJiraNumber = await matchJira(params)
        if (!isMatchJiraNumber) {
          throw new Error(this.$t('custom.component.gadget.checkNumber'))
        }
        callback()
      } catch (error) {
        callback(error)
      }
    },
    async getBusinessTypes () {
      const value = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_type_list')
      if (value) {
        const list = value.dataList || []
        if (this.form.businessType === 'MSPbots Internal' && this.$hasPermission('sys:report:type:mspbots internal')) {
          return list.filter(item => item.dictValue === 'MSPbots Internal')
        }

        return list.filter(item => item.dictValue !== 'MSPbots Internal')
      }
      return []
    },
    async getStatusList () {
      const value = window.SITE_CONFIG['dictList'].find(e => e.dictType === 'datasets_status_list')
      if (value) {
        const list = value.dataList || []
        if (this.$hasPermission('sys:reports:publishauth')) {
          return list
        }

        return list.filter(item => item.dictValue !== 'Alpha' && item.dictValue !== 'Published')
      }
      return []
    },
    async getRoles () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      const { data: response } = await fetchRole(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getAssingRoles () {
      const roleIds = (this.$store.state.user.roleList || []).map(({ id }) => id)
      const params = {
        roleId: roleIds
      }
      const { data: response } = await fetchAssignRole(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getTags () {
      const params = {
      }
      const { data: response } = await fetchTag(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async getUsers () {
      const params = {
        datasetKey: 'qwerdsafsadrtfzgsadfggs'
      }
      const { data: response } = await fetchQuery(params)
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },

    async getBotTemplates () {
      const { data: response } = await fetchBotTemplates()
      if (response.code !== 0) {
        return []
      }
      return response.data || []
    },
    async onReselect () {
      this.$emit('event:reselect')
    },
    async onSave () {
      try {
        this.moreEditVisible ? this.moreLoading = true : this.loading = true

        await this.$refs[this.moreEditVisible ? 'moreForm' : 'form'].validate()

        await this.validateForm()

        const { ...rest } = this.form
        const params = {
          ...rest,
          resourceType: this.resourceType
        }


        const { id, _type, triggerEvent, name } = this.row || {}

        if (_type === 'Store' || _type === 'template') {
          set(params, 'originalId', id)
          set(params, 'newType', _type === 'Store' ? 3 : 2)
        }

        if (_type === 'script') {
          const flowSettingObj = getFlowSetting(triggerEvent, cloneDeep(this.row))

          set(params, 'triggerType', triggerEvent)
          set(params, 'newType', 1)
          set(params, 'flowSetting', flowSettingObj.flowSetting)
          set(params, 'sysBotScriptList', [
            {
              botId: '',
              name,
              paramsValue: flowSettingObj.paramsvaluesend,
              scriptId: id,
              trackId: flowSettingObj.trackid,
              triggerId: ''
            }
          ])
        }

        const { data: response } = await createBot(params)
        if (response.code !== 0) {
          throw response.msg
        }
        if (response.data.exist) {
          throw this.$t('custom.dataset.nameexist')
        }
        this.$message.success(response.msg)
        this.$emit('event:success', response.data)
      } catch (error) {
        useErrorMessage(error)
      } finally {
        this.moreEditVisible ? this.moreLoading = false : this.loading = false
      }
    },
    async validateForm () {
      if (this.$store.state.user.username.includes('mspbots.ai') && this.$hasPermission('sys:bots:moreedit')) {
        const { da, po, jiraNumber, tenantCode, businessType, description, roleIdList, name, id } = this.form

        if (tenantCode === '1001' && businessType === 'Custom' && this.$store.state.user.tenantCode !== '1001') {
          throw 'The login person is the default tenant, then the type of widget cannot be Custom.'
        }

        if (!this.moreEditVisible) {
          if (!da) {
            throw this.$t('custom.component.gadget.da')
          }
          if (!po) {
            throw this.$t('custom.component.gadget.po')
          }
          if (jiraNumber !== 'NA') {
            let params = {
              issueIdOrKey: jiraNumber
            }

            const isMatchJiraNumber = await matchJira(params)
            if (!isMatchJiraNumber) {
              throw this.$t('custom.component.gadget.checkNumber')
            }
          }
        } else {
          if (!name) {
            throw 'Name ' + this.$t('validate.required')
          }
          if (!symbolReg.test(name)) {
            throw 'Name' + this.$t('validate.isIncludeSymbol')
          }

          let params = {
            name,
            id,
            businessType
          }

          const { data: response } = await checkBotName(params)
          if (response.code !== 0) {
            throw 'The name is already exists'
          }

          if (!roleIdList.length) {
            throw 'Role ' + this.$t('validate.required')
          }
          // if (!description) {
          //   throw 'Description ' + this.$t('validate.required')
          // }
        }
      }

    }

  }
}
</script>

<style lang="scss">
.more-dialog {
  .el-dialog__body {
    padding: 20px 0 20px 20px;
  }
}
.more-edit-dialog-form {
  height: 400px;
  padding-right: 15px;
  overflow: auto;
  .el-row {
    margin: 0;
  }

  &::-webkit-scrollbar {
    width: 5px;
    height: 5px;
  }

  &::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background-color: #17b3a3;
    background-image: -webkit-linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.4) 25%,
      rgba(255, 255, 255, 0.4)
    );
  }

  &::-webkit-scrollbar-track {
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #ededed;
    border-radius: 10px;
  }
}
</style>
